<template>
    <el-dialog v-model="localVisible" title="修改用户" width="30%" center @close="handleCancel">
      <el-form :model="UpdateForm" :rules="UpdateRules" ref="UpdateFormRef" label-position="top" label-width="0px">
        <el-form-item label="用户ID" prop="id">
          <el-input v-model="UpdateForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="UpdateForm.name"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="UpdateForm.email" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="UpdateForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户角色" prop="role">
          <el-select v-model="UpdateForm.role" placeholder="请选择用户角色">
            <el-option label="普通用户" value="普通用户"></el-option>
            <el-option label="会员" value="会员"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span class="dialog-footer">
        <el-button type="primary" @click="onUpdate">确定</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </span>
    </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue';
import axios from 'axios';
import { defineProps, defineEmits } from 'vue';
import { ElMessage } from 'element-plus'

const api = axios.create({
    baseURL:'http://localhost:8092',
    headers: {
        'Authorization': `${localStorage.getItem('token')}`
    }
})

const props = defineProps({
  updateName: String,
  updateEmail: String,
  updatePhone: String,
  updateRole: String,
  visible: Boolean,
  userId: Number // 确保这里正确声明了 userId
});

const emit = defineEmits(['update:visible', 'edit']); // 注意这里是 edit 而不是 add

const localVisible = ref(props.visible);

watch(() => props.visible, (newValue) => {
    localVisible.value = newValue;
});

watch(localVisible, (newValue) => {
if (!newValue) {
    emit('update:visible', false);
}
});
// 监听 props 变化并更新 UpdateForm
watch([() => props.userId, () => props.updateRole, () => props.updatePhone, () => props.updateEmail, () => props.updateName]
, ([newUserId, newRole, newPhone, newEmail, newName]) => {
    UpdateForm.value.id = newUserId || '';
    UpdateForm.value.role = newRole !== undefined ? newRole : '';
    UpdateForm.value.phone = newPhone || '';
    UpdateForm.value.email = newEmail !== undefined ? newEmail : '';
    UpdateForm.value.name = newName || '';
});

const UpdateForm = ref({
  id: props.userId || '',
  name: props.updateName !== undefined ? props.updateName : '',
  email: props.updateEmail || '',
  phone: props.updatePhone !== undefined ? props.updatePhone : '',
  role: props.updateRole || ''
});
const UpdateRules = {
  name: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  role: [
    { required: true, message: '请输入角色信息', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (!['普通用户', '会员'].includes(value)) {
          callback(new Error('角色必须为普通用户或会员'));
        } else {
          callback();
        }
      }, 
      trigger: 'change'
    }
  ]
};

const UpdateFormRef = ref(null);

const onUpdate = () => {
    const requestData = {
        id: props.userId,
        ...UpdateForm.value
    };
    UpdateFormRef.value.validate((valid) => {
        if (valid) {
        api.put('/api/v1/user/user-info', requestData
            ).then(response => {
            if (response.data.code == "200"){
                ElMessage({
                title: '成功',
                message: '修改成功',
                type: 'success',
                showClose: false,
                });
                localVisible.value = false;
                emit('edit'); // 通知父组件数据已更新
            } else {
                ElMessage({
                title: '错误',
                message: '修改失败！' + response.data.message,
                type: 'error',
            });
            }
            }).catch(error => {
            ElMessage({
                title: '错误',
                message: '修改失败！' + error.message,
                type: 'error',
            });
            });
        } else {
        return false;
        }
    });
};

const handleCancel = () => {
    localVisible.value = false;
};
</script>
  
<style scoped>
  .dialog-footer {
    display: flex;
    justify-content: space-evenly; 
    margin-top: 20px; 
  }
  
  .dialog-footer .el-button {
    width: 30%;
    height: 45px;
    font-size: 16px;
    margin-top: 20px; 
  }
</style>